package com.funsport.service;

import com.funsport.entity.UserRole;
import com.funsport.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户角色服务
 */
@Service
public class UserRoleService {
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    /**
     * 获取用户的角色ID列表
     */
    public List<Long> getUserRoleIds(Long userId) {
        return userRoleMapper.selectRoleIdsByUserId(userId);
    }
    
    /**
     * 分配角色给用户
     */
    @Transactional
    public void assignRoles(Long userId, List<Long> roleIds) {
        // 先删除用户的所有角色
        userRoleMapper.deleteByUserId(userId);
        
        // 重新分配角色
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                UserRole ur = new UserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                userRoleMapper.insert(ur);
            }
        }
    }
    
    /**
     * 添加用户角色
     */
    public void addUserRole(Long userId, Long roleId) {
        UserRole ur = new UserRole();
        ur.setUserId(userId);
        ur.setRoleId(roleId);
        userRoleMapper.insert(ur);
    }
    
    /**
     * 移除用户角色
     */
    public void removeUserRole(Long userId, Long roleId) {
        userRoleMapper.deleteByUserIdAndRoleId(userId, roleId);
    }
}

